package com.century.sjt.activity.Pay;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.century.sjt.R;
import com.century.sjt.activity.BaseActivity;
import com.century.sjt.adapter.GoodSortListViewAdapter;
import com.century.sjt.adapter.aQueryCommodityAdapter;
import com.century.sjt.entity.Commodit;
import com.century.sjt.entity.MyOrderInfo;
import com.century.sjt.entity.goodSort;
import com.century.sjt.util.Constant;
import com.century.sjt.util.TipUtil;
import com.century.sjt.waterfall.lib.internal.PLA_AdapterView;
import com.century.sjt.waterfall.util.ImageFetcher;
import com.century.sjt.waterfall.view.XListView;
import com.century.sjt.widget.ListViewForScrollView;
import com.century.sjt.widget.TitleBar.SjtTitleBar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by asus on 2016/9/13.
 */
public class aQueryCommoditActivity extends BaseActivity implements XListView.IXListViewListener {
    private XListView mAdapterView;
    private aQueryCommodityAdapter mAdapter;
    private GoodSortListViewAdapter adapter;
    private ListViewForScrollView GoodSortList;
    private int currentPage = 1;
    private SjtTitleBar titleBar;
    private ImageFetcher mImageFetcher;
    private Handler mHandler;
    private Boolean isDataChangeOk = true;        //是否加载成功
    private List<Commodit> result = new ArrayList<>();
    private List<Commodit> selectList = new ArrayList<>();
    private List<goodSort> goodSortList = new ArrayList<>();
    private String shopId;//分店id
    private EditText aQueryText;
    private LinearLayout btn_search;
    private TextView btn_search_icon;
    private SwipeRefreshLayout mSwipeLayout;        //刷新组件

    //    private ImageButton search_clear;
    private String aQueryName = "";
    private String goodSortId = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.aquery_pull_to_refresh_sample);
        Intent intent = getIntent();
        shopId = intent.getStringExtra("shopId");
        //获得从activity中传递过来的值
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 1:
                        mAdapter.notifyDataSetChanged();
                        break;
                    case 2:
                        isDataChangeOk = true;
                        result.clear();
                        currentPage = 1;
                        getCommodit(1, aQueryName);
                        break;
                    case 3:
                        if (isDataChangeOk) {
                            currentPage++;
                            getCommodit(2, aQueryName);
                        }
                        break;
                    case 4:
                        adapter.notifyDataSetChanged();
                        mSwipeLayout.setRefreshing(false);
                        break;
                    case 5:
                        isDataChangeOk = true;
                        goodSortList.clear();
                        mSwipeLayout.setRefreshing(true);
                        currentPage = 1;
                        goodSortList();
                        break;
                    case 6:
                        if (isDataChangeOk) {
                            currentPage++;
                            goodSortList();
                        }
                        break;
                }
            }
        };


        initView();
        initEvent();
        initData();
        mAdapterView.setVisibility(View.GONE);
        GoodSortList.setVisibility(View.VISIBLE);
        Message msg = new Message();
        msg.what = 5;
        mHandler.sendMessage(msg);
//        getCommodit(1,aQueryName);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        mImageFetcher.setExitTasksEarly(false);
        GoodSortList.setFocusable(false);
//        AddItemToContainer(currentPage, 2);
//        Message msg = new Message();
//        msg.what = 2;
//        mHandler.sendMessage(msg);
//        getCommodit(currentPage, 1);
    }

    @Override
    protected void initView() {
        titleBar = (SjtTitleBar) findViewById(R.id.title_bar);
        titleBar.setTitle(getResources().getString(R.string.tab_commodit));
        titleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //刷新组件
        mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.activity_list_refesh);
        aQueryText = (EditText) findViewById(R.id.query);
//        search_clear = (ImageButton) findViewById(R.id.search_clear);
        mImageFetcher = new ImageFetcher(this, 240);
        mImageFetcher.setLoadingImage(R.drawable.empty_photo);
        btn_search = (LinearLayout) findViewById(R.id.btn_submit);
        btn_search_icon = (TextView) findViewById(R.id.btn_submit_icon);
        SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
        String isMerchant = mainSharedPreferences.getString("isMerchant", "");
        String isShop = mainSharedPreferences.getString("isShop", "");
        Typeface iconfont = Typeface.createFromAsset(getAssets(), "iconfont.ttf");
        btn_search_icon.setTypeface(iconfont);
//        Log.d("Tag","是否是商家："+isMerchant+"是否是分店："+isShop);
        //判断是商家、分店还是用户
//        if (isMerchant.equals("0")&isShop.equals("0")){
//            layout_Order.setVisibility(View.VISIBLE);
//        }else{
//            layout_Order.setVisibility(View.GONE);
//        }
        GoodSortList = (ListViewForScrollView) findViewById(R.id.goodsotr_list);
        adapter = new GoodSortListViewAdapter(this, mQueue, goodSortList);
        GoodSortList.setAdapter(adapter);
        mAdapterView = (XListView) findViewById(R.id.list);
        mAdapterView.setPullLoadEnable(true);
        mAdapterView.setXListViewListener(this);
        mAdapter = new aQueryCommodityAdapter(this, mAdapterView, mHandler, mImageFetcher, result);
        mAdapterView.setAdapter(mAdapter);

        GoodSortList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                goodSortId = goodSortList.get(position).getSysId();
                mAdapterView.setVisibility(View.VISIBLE);
                GoodSortList.setVisibility(View.GONE);
                mSwipeLayout.setVisibility(View.GONE);
                Message msg = new Message();
                msg.what = 2;
                mHandler.sendMessage(msg);
            }
        });


//        adapter.setItemClickListener(new GoodSortListViewAdapter.ItemClickListener() {
//            @Override
//            public void onClick(int id) {
////                goodSortId = goodSortList.get(id).getSysId();
////                mAdapterView.setVisibility(View.VISIBLE);
////                GoodSortList.setVisibility(View.GONE);
////                mSwipeLayout.setVisibility(View.GONE);
////                Message msg = new Message();
////                msg.what = 2;
////                mHandler.sendMessage(msg);
//            }
//        });
        mAdapterView.setOnItemClickListener(new PLA_AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(PLA_AdapterView<?> parent, View view, int position, long id) {
                int i = position - 1;
                Intent intent = new Intent(aQueryCommoditActivity.this, CommodityActivity.class);
                intent.putExtra("url", result.get(i).getDetailsUrl());
                intent.putExtra("shopId", result.get(i).getShopId());
                intent.putExtra("goodId", result.get(i).getGoodId());
                intent.putExtra("shareUrl", result.get(i).getShareUrl());
                intent.putExtra("goodName", result.get(i).getGoodName());
                intent.putExtra("mainImageUrl", result.get(i).getMainImageUrl());
                intent.putExtra("shopUserId", result.get(i).getShopUserId());
                intent.putExtra("price", result.get(i).getPrice());
                startActivity(intent);
            }
        });
        //软键盘设置
        aQueryText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                 /*判断是否是“GO”键*/
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    /*隐藏软键盘*/
                    InputMethodManager imm = (InputMethodManager) v
                            .getContext().getSystemService(
                                    Context.INPUT_METHOD_SERVICE);
                    if (imm.isActive()) {
                        imm.hideSoftInputFromWindow(
                                v.getApplicationWindowToken(), 0);
                    }

//                    edittext.setText("success");
//                    webview.loadUrl(URL);
                    if ("".equals(aQueryName) || null == aQueryName) {
                        TipUtil.showToast(getResources().getString(R.string.error_input_search), aQueryCommoditActivity.this, 1);
                    } else {
                        Message msg = new Message();
                        msg.what = 2;
                        mHandler.sendMessage(msg);
                    }
                    return true;
                }
                return false;
            }
        });
        aQueryText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                aQueryName = aQueryText.getText().toString();
//                if (aQueryText.getText().toString().length()>0)
//                    search_clear.setVisibility(View.VISIBLE);
//                aQueryName = aQueryText.getText().toString();
//                Message msg = new Message();
//                msg.what = 2;
//                mHandler.sendMessage(msg);
            }
        });
//        search_clear.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                aQueryText.setText("");
//                aQueryName="";
//            }
//        });
        btn_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("".equals(aQueryName) || null == aQueryName) {
                    TipUtil.showToast(getResources().getString(R.string.error_input_search), aQueryCommoditActivity.this, 1);
                } else {
                    mAdapterView.setVisibility(View.VISIBLE);
                    GoodSortList.setVisibility(View.GONE);
                    mSwipeLayout.setVisibility(View.GONE);
                    Message msg = new Message();
                    msg.what = 2;
                    mHandler.sendMessage(msg);
                }
            }
        });

        //刷新组件
        mSwipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Message msg = new Message();
                msg.what = 5;
                mHandler.sendMessage(msg);
            }
        });
        mSwipeLayout.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light,
                android.R.color.holo_orange_light, android.R.color.holo_red_light);


    }

    @Override
    protected void initEvent() {


    }

    private interface OrderClickListener {
        void onSuccess(MyOrderInfo orderInfo);
    }

    @Override
    protected void initData() {

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    @Override
    public void onRefresh() {
//        AddItemToContainer(currentPage=0, 1);
        if ("".equals(aQueryName) || null == aQueryName) {
            TipUtil.showToast(getResources().getString(R.string.error_input_search), aQueryCommoditActivity.this, 1);
            mAdapterView.stopRefresh();
        } else {
            Message msg = new Message();
            msg.what = 2;
            mHandler.sendMessage(msg);
        }

    }

    @Override
    public void onLoadMore() {
//        AddItemToContainer(++currentPage, 2);
        if ("".equals(aQueryName) || null == aQueryName) {
            TipUtil.showToast(getResources().getString(R.string.error_input_search), aQueryCommoditActivity.this, 1);
            mAdapterView.stopLoadMore();
            mAdapter.notifyDataSetChanged();
        } else {
            if (isDataChangeOk) {
                Message msg = new Message();
                msg.what = 3;
                mHandler.sendMessage(msg);
            } else {
                mAdapterView.stopLoadMore();
                mAdapter.notifyDataSetChanged();
            }
        }


    }

    /**
     * 获取商品列表
     *
     * @param
     */
    private void getCommodit(final int type, final String goodName) {

        isDataChangeOk = false;        //是否更新成功
//        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.error_please_waitting), CommodityListActivity.this);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.ShopGoods, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    TipUtil.log("接口返回", response, 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
//
                    if (code.equals("200")) {//成功
                        isDataChangeOk = true;
                        JSONObject data = res.getJSONObject("data");
                        if (data.length() > 1) {
                            shopId = data.getString("shopId");
                            String shopUserId = data.getString("shopUserId");
                        }
                        JSONArray goodList = data.getJSONArray("goodList");
                        if (goodList.length() != Constant.PAGESIZE) {
                            isDataChangeOk = false;
                        }
                        if (goodList.length() != 0) {
                            for (int i = 0; i < goodList.length(); i++) {
                                JSONObject good = (JSONObject) goodList.get(i);
                                Commodit commodit = new Commodit();
                                commodit.setPrice(good.getString("price"));
                                commodit.setOriginalPrice(good.getString("originalPrice"));
                                commodit.setDescription(good.getString("description"));
                                commodit.setDetailsUrl(good.getString("detailsUrl"));
                                commodit.setHeight(good.getInt("imageHeight"));
                                commodit.setWidth(good.getInt("imageWidth"));
                                commodit.setMainImageUrl(good.getString("mainImageUrl"));
                                commodit.setGoodName(good.getString("goodName"));
                                commodit.setCurrency(good.getString("currency"));
                                commodit.setSelect(false);
                                commodit.setGoodId(good.getString("goodId"));
                                commodit.setShareUrl(good.getString("shareUrl"));
                                commodit.setShopId(good.getString("shopId"));
                                commodit.setShopName(good.getString("shopName"));
                                commodit.setShopUserId(good.getString("shopUserId"));
                                result.add(commodit);
                            }

                        }

                    } else {//失败
                        isDataChangeOk = false;

                        currentPage--;
                        if (type == 1) {
                            mAdapterView.stopRefresh();
                        } else if (type == 2) {
                            mAdapterView.stopLoadMore();
                        }
                        Toast.makeText(aQueryCommoditActivity.this, message, Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException ex) {
                    ex.printStackTrace();
                    Toast.makeText(aQueryCommoditActivity.this, getResources().getString(R.string.error_service), Toast.LENGTH_LONG).show();
                }
                if (type == 1) {
                    mAdapter.notifyDataSetChanged();
                    mAdapterView.stopRefresh();
                } else if (type == 2) {
                    mAdapterView.stopLoadMore();
                    mAdapter.notifyDataSetChanged();
                }
                Message msg = new Message();
                msg.what = 1;
                mHandler.sendMessage(msg);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if (type == 1) {
                    mAdapterView.stopRefresh();
                } else if (type == 2) {
                    mAdapterView.stopLoadMore();
                }
                currentPage--;
                Message msg = new Message();
                msg.what = 1;
                mHandler.sendMessage(msg);
                TipUtil.showToast(getResources().getString(R.string.error_network), aQueryCommoditActivity.this, 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
//                map.put("loginId", userId);
                if (!"".equals(shopId))
                    map.put("shopId", shopId);
                if (!"".equals(goodName))
                    map.put("goodName", goodName);
                if (!"".equals(goodSortId))
                    map.put("goodSortId", goodSortId);
                map.put("paging.currentPage", currentPage + "");
                map.put("paging.pageSize", Constant.PAGESIZE + "");
                return map;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = getSharedPreferences(com.century.sjt.util.Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);
    }

    /**
     * 获取商品分类
     */
    private void goodSortList() {
//        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.error_please_waitting), aQueryCommoditActivity.this);
        isDataChangeOk = false;
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.goodSortList, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {
                        isDataChangeOk = true;
                        JSONObject data = res.getJSONObject("data");
                        JSONArray mgoodSortList = data.getJSONArray("goodSortList");
                        if (mgoodSortList.length() != Constant.PAGESIZE)
                            isDataChangeOk = false;
                        for (int i = 0; i < mgoodSortList.length(); i++) {
                            JSONObject item = (JSONObject) mgoodSortList.get(i);
                            goodSort goodSort = new goodSort();
                            goodSort.setSysId(item.getString("sortId"));
                            goodSort.setDescription(item.getString("description"));
                            goodSort.setSortName(item.getString("sortName"));
                            goodSort.setImage(item.getString("image"));
                            //goodSort.setSort(item.getString("sort"));
                            goodSortList.add(goodSort);
                        }
                    } else {
                        isDataChangeOk = false;
                        currentPage--;
                        TipUtil.showToast(message, aQueryCommoditActivity.this, 1);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service), aQueryCommoditActivity.this, 1);
                }
                Message msg = new Message();
                msg.what = 4;
                mHandler.sendMessage(msg);
//                TipUtil.closeProgressDialog();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), aQueryCommoditActivity.this, 1);
                TipUtil.closeProgressDialog();
                currentPage--;
                Message msg = new Message();
                msg.what = 4;
                mHandler.sendMessage(msg);
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
//                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
//                String userId = mainSharedPreferences.getString("userId", "");
//                map.put("loginId", userId);
//                map.put("shopId", shopId);//分店id
//                map.put("goodId", goodId);//商品id
                map.put("paging.currentPage", currentPage + "");
                map.put("paging.pageSize", Constant.PAGESIZE + "");
                return map;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);
    }

}
